﻿using System;
using System.Text.RegularExpressions;

namespace IssueIT.Core.Domain.Model
{
	public class EmailAddress
	{
		private static readonly Regex EmailPattern = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled);

		public static EmailAddress None = new EmailAddress();

		protected EmailAddress()
		{
		}

		public EmailAddress(string address, string displayName) : this(address)
		{
			DisplayName = displayName;
		}

		public EmailAddress(string address)
		{
			EnsureValidEmail(address);
			Address = address;
		}

		private static void EnsureValidEmail(string address)
		{
			if( !EmailPattern.IsMatch(address) )
			{
				throw new FormatException(string.Format("Mail address '{0}' invalid format", address));
			}
		}

		public string Address { get; private set; }
		public string DisplayName { get; private set; }

		public bool Equals(EmailAddress other)
		{
			if( ReferenceEquals(null, other) )
			{
				return false;
			}
			if( ReferenceEquals(this, other) )
			{
				return true;
			}

			return string.Equals(other.Address, Address, StringComparison.OrdinalIgnoreCase) && Equals(other.DisplayName, DisplayName);
		}

		public override bool Equals(object obj)
		{
			return Equals(obj as EmailAddress);
		}

		public override int GetHashCode()
		{
			unchecked
			{
				return ((Address!=null ? Address.GetHashCode() : 0) * 397) ^ (DisplayName!=null ? DisplayName.GetHashCode() : 0);
			}
		}
	}
}